package com.jeomo.shiro.bean;

import com.jeomo.common.core.util.BeanCopyUtil;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.shiro.dto.LoginInfo;
import com.jeomo.shiro.enums.PlatformEnum;
import com.jeomo.shiro.util.PasswordUtil;
import com.jeomo.sys.api.bo.UserBo;
import com.jeomo.sys.starter.entity.Org;
import com.jeomo.sys.starter.entity.User;
import com.jeomo.sys.starter.service.IOrgService;
import com.jeomo.sys.starter.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 管理用户登录
 * @author QBT
 */
@Component
public class ManageUserRealm extends ShiroServiceBaseUserRealm {

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrgService orgService;


    public ManageUserRealm() {
        super(PlatformEnum.MANAGE);
    }

    /**
     * 执行认证逻辑
     * @param authcToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        CustomizedUsernamePasswordToken token = (CustomizedUsernamePasswordToken) authcToken;
        String username = (String) token.getUsername();
        String orgCode = token.getOrgCode();
        Org org = orgService.getById(orgCode);
        if(org == null) {

        }
        if (StringUtils.isEmpty(username)) {
            throw new UnknownAccountException("用户名不能为空");
        }
        User user = userService.queryByUsername(username);
        if(user == null) {
            throw new UnknownAccountException("用户名或密码错误");
        }
        LoginInfo loginInfo = buildLoginInfo(token.getLoginPlatform(), user);
        String salt = PasswordUtil.getSalt(user.getTopOrgCode(), user.getUsername());
        SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(loginInfo, user.getPassword(), ByteSource.Util.bytes(salt), user.getUsername());
        // 清缓存中的授权信息，保证每次登陆 都可以重新授权。因为AuthorizingRealm会先检查缓存有没有 授权信息，再调用授权方法
        super.clearCachedAuthorizationInfo(authcInfo.getPrincipals());
        return authcInfo;
    }

    private LoginInfo buildLoginInfo(PlatformEnum loginPlatform, User user) {
        Org org = orgService.getById(user.getOrgCode());
        LoginInfo loginInfo = new LoginInfo();
        UserBo bo = BeanCopyUtil.copyProperties(user, UserBo.class);
        loginInfo.setLoginUser(bo);
        loginInfo.setLoginPlatform(loginPlatform);
        loginInfo.setLoginTime(new Date());
        loginInfo.setCurrentTopOrgCode(org.getTopOrgCode());
        loginInfo.setCurrentOrgCode(org.getCode());
        return loginInfo;
    }


}
